package com.htgd.gardenexpo.config;
import com.htgd.gardenexpo.utils.RSAUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class DecryptingFilter implements Filter{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        if ("POST".equalsIgnoreCase(httpRequest.getMethod())) {
            // 检查 Content-Type 是否为 multipart/form-data
            String contentType = httpRequest.getContentType();
            if (contentType != null && contentType.startsWith("multipart/form-data")) {
                // 直接处理 multipart/form-data 请求，跳过解密
                chain.doFilter(request, response);
                return;
            }

            // 处理普通的 POST 请求
            DecryptingRequestWrapper wrappedRequest = new DecryptingRequestWrapper(httpRequest);
            String requestBody = wrappedRequest.getCachedBody();

            // 检查请求体中是否包含 encryption 字段并进行解密
            if (requestBody.contains("encryption")) {
                try {
                    requestBody = RSAUtil.decryption(requestBody);
                } catch (Exception e) {
                    response.getWriter().append("解密失败").flush();
                    return; // 返回解密失败
                }

                // 用解密后的内容包装请求
                wrappedRequest = new DecryptingRequestWrapper(wrappedRequest, requestBody);
            }

            // 继续处理过滤链，传递解密后的请求
            chain.doFilter(wrappedRequest, response);
        } else {
            // 直接处理非 POST 请求
            chain.doFilter(request, response);
        }
    }
}
